//
//  ZGLMainViewController.m
//  ZeegingLottery
//
//  Created by 蒂埃里 on 2018/3/29.
//  Copyright © 2018年 蒂埃里. All rights reserved.
//

#import "ZGLMainViewController.h"
#import "ZGLAgainstCell.h"
#import "ZGLDataModel.h"
#import "ZGLConfirmSelectView.h"
#import "ZGLConfirmListController.h"

@interface ZGLMainViewController ()<UIGestureRecognizerDelegate>

// <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)ZGLConfirmSelectView *confirmView;

@property (nonatomic, strong)YUFoldingTableView *AgainstListView;
@property (nonatomic, assign)YUFoldingSectionHeaderArrowPosition arrowPosition;
@property (nonatomic, assign) NSInteger index;

@property (strong, nonatomic)NSMutableArray <ZGLDataModel *> *dataModelArr;
@property (strong, nonatomic)NSMutableArray <ZGLAgainstModel *>*selectionArray;  //选中场次

@end

@implementation ZGLMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"首页";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.AgainstListView];
    [self.view addSubview:self.confirmView];
    [self setupUI];

//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"me_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController)];
    
    //右滑手势
    UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFromleft:)];
    [recognizer setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:recognizer];
    
    //菊花
    [EasyLoadingView showLoadingText:@"正在努力加载中..." config:^EasyLoadingConfig *{
        return [EasyLoadingConfig shared].setLoadingType(LoadingShowTypeIndicator);
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //侧滑
//        [self registerSlideToleft];
        
        //真数据
        [self getTheBattleList];
        
    });
    
    //监听更新数据源
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDataSource:) name:ZGLUpdateDataSource object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanAllSelected) name:ZGLPaySuccessNotifi object:nil];
    
}


- (void)dealloc {
    DLog(@"%s",__func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - YUFoldingTableViewDelegate


- (NSInteger)numberOfSectionForYUFoldingTableView:(YUFoldingTableView *)yuTableView
{
    return self.dataModelArr.count;
    
}

- (NSInteger)yuFoldingTableView:(YUFoldingTableView *)yuTableView numberOfRowsInSection:(NSInteger)section
{
    ZGLDataModel *model = self.dataModelArr[section];
    NSInteger count = model.data.count;
    
    return count;
    
}

- (CGFloat )yuFoldingTableView:(YUFoldingTableView *)yuTableView heightForHeaderInSection:(NSInteger )section
{
    return 30;
}
- (CGFloat )yuFoldingTableView:(YUFoldingTableView *)yuTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}

- (UITableViewCell *)yuFoldingTableView:(YUFoldingTableView *)yuTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZGLAgainstCell *cell = [ZGLAgainstCell againstCellWithTableView:yuTableView indexPath:indexPath];
    
    ZGLDataModel *dataModel = self.dataModelArr[indexPath.section];
    NSMutableArray <ZGLAgainstModel *>*models = dataModel.data;
    ZGLAgainstModel *model = models[indexPath.row];
    [model setIndexPath:indexPath];
    model.draw = dataModel.draw;
    WS(weakself)
    cell.modelsBlock = ^(NSInteger num) {
        
        weakSelf.confirmView.selectedNum = num;
    };
    cell.model = model;
    
    return cell;
}

// 返回箭头的位置
- (YUFoldingSectionHeaderArrowPosition)perferedArrowPositionForYUFoldingTableView:(YUFoldingTableView *)yuTableView
{
    // 没有赋值，默认箭头在左
    return self.arrowPosition ? :YUFoldingSectionHeaderArrowPositionLeft;
}

- (NSString *)yuFoldingTableView:(YUFoldingTableView *)yuTableView titleForHeaderInSection:(NSInteger)section
{
    ZGLDataModel *model = self.dataModelArr[section];
    NSString *timeStr = model.draw;
    NSString *year=[timeStr substringToIndex:4];
    NSString *month=[timeStr substringWithRange:NSMakeRange(4, 2)];
    NSString *day=[timeStr substringFromIndex:6];
    NSString *weekdate=[PublicMethod weekdayStringFromDate:timeStr dateFormat:@"yyyyMMdd"];
    return [NSString stringWithFormat:@"%@年%@月%@日 %@",year,month,day,weekdate];
}

#pragma mark - method

//更新数据源
- (void)updateDataSource:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.object;
    DLog(@"userInfo--%@",userInfo);
    
    NSIndexPath *indexPath = userInfo[@"indexPath"];
    ZGLAgainstModel *callBackModel = userInfo[@"Againstmodel"];
    
    //替换model
    ZGLDataModel *dataModel = self.dataModelArr[indexPath.section];
    NSMutableArray <ZGLAgainstModel *>*models  = dataModel.data;
    [models replaceObjectAtIndex:indexPath.row withObject:callBackModel];
//    dataModel.data = models;
//    self.dataModelArr[indexPath.section] = dataModel;
    
    DLog(@"替换后的model--%@---",models[indexPath.row]);
    
    [self.AgainstListView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}


//清空
- (void)cleanAllSelected
{
    [ApplicationDelegate.jsonContentArr removeAllObjects];
    ApplicationDelegate.jsonContentArr = nil;
    [self.AgainstListView reloadData];
//    [self.AgainstListView setNeedsLayout];
    NSInteger count = ApplicationDelegate.jsonContentArr.count;
    self.confirmView.selectedNum = count;
    
    DLog(@"清空后ApplicationDelegate.jsonContentArr--%@--count--%ld",ApplicationDelegate.jsonContentArr,ApplicationDelegate.jsonContentArr.count);
    
    //1.清空，发通知
    [[NSNotificationCenter defaultCenter] postNotificationName:ZGLCleanAllSelectOdd object:nil];
    
}

//右滑手势
- (void)handleSwipeFromleft:(UISwipeGestureRecognizer *)gesture
{
    DLog(@"swipe right");
//    [self registerSlideToleft];
    [self presentLeftMenuViewController];
}


//侧滑抽屉
- (void)registerSlideToleft
{
    WS(weakself)
    [self cw_registerShowIntractiveWithEdgeGesture:NO transitionDirectionAutoBlock:^(CWDrawerTransitionDirection direction) {
        if (direction == CWDrawerTransitionFromLeft) {
            
            [weakSelf presentLeftMenuViewController];
        }
    }];
}


//跳转抽屉
- (void)presentLeftMenuViewController
{
    ZGLLeftMenuController *leftVc = [[ZGLLeftMenuController alloc]init];
    [self cw_showDrawerViewController:leftVc animationType:CWDrawerAnimationTypeMask configuration:nil];
    
}

//选好了
- (void)confirmBtn:(UIButton *)sender
{
    DLog(@"确认选择");
    
    //计算注数和奖金
    NSInteger count = ApplicationDelegate.jsonContentArr.count;
    NSString *ggTyep = [NSString stringWithFormat:@"%ld001",count];
    NSString *json = [Calculator betContentJSONWith:ApplicationDelegate.jsonContentArr];
    NSDictionary *jsonDict = [Calculator calculator:json ggType:ggTyep times:10 lotteryId:46];
    NSMutableDictionary *mtJsonDict = jsonDict.mutableCopy;
    
    int betNum = [jsonDict[@"bet_num"] intValue];
    int totalMoney = 2*10*betNum; //总金额
    
    [mtJsonDict setValue:@(totalMoney) forKey:@"amount"];
    [mtJsonDict setObject:json forKey:@"content"];
    DLog(@"%@",jsonDict);
    
    
    ZGLConfirmListController *confirmVC = [[ZGLConfirmListController alloc]init];
    WS(weakself)
    confirmVC.selectedCountBlock = ^(NSInteger num) {
        
        weakSelf.confirmView.selectedNum = num;
    };
    confirmVC.confirmMatchArr = ApplicationDelegate.jsonContentArr;
    confirmVC.betJSONDict = mtJsonDict.copy;
    
    //埋点
    NSDictionary *parame = @{
                             @"LottCount": @(count)
                             };
    [TalkingData trackEvent:ZGLMainPageConfirmBtnEventID label:@"选好了" parameters:parame];
    
    
    [self.navigationController pushViewController:confirmVC animated:YES];
    
}

//清空
- (void)qingKong:(UIButton *)sender
{
    DLog(@"清空所有");
    [TalkingData trackEvent:ZGLMainPageCleanAllBtnEventID];
    
    [self cleanAllSelected];
}

//获取对战列表
- (void)getTheBattleList
{
    
    WS(weakself)
    [sZGLHTTPRequestManager GetTheBattleListSuccess:^(id responseData) {
        
        DLog(@"responseData-%@",responseData);
        
        [_dataModelArr removeAllObjects];
        _dataModelArr = [ZGLDataModel mj_objectArrayWithKeyValuesArray:responseData];
//        DLog(@"最新_dataModelArr——%@",self.dataModelArr);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //停止菊花转
            [EasyLoadingView hidenLoading];
            [weakSelf.AgainstListView reloadData];
            //停止刷新
            [weakSelf.AgainstListView.mj_header endRefreshing];
            
        });
        
    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
        
        DLog(@"暂无数据");
        
        
    }];
    
}

#pragma mark - 懒加载

- (NSMutableArray<ZGLDataModel *> *)dataModelArr
{
    if (!_dataModelArr) {
        _dataModelArr = [NSMutableArray array];
    }
    return _dataModelArr;
}

- (NSMutableArray *)selectionArray
{
    if (!_selectionArray) {
        _selectionArray = [NSMutableArray array];
    }
    return _selectionArray;
}

- (void)setupUI{
    
    [_confirmView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
//        make.bottom.equalTo(self.view).offset(-STATUEHEIGHT);
        make.height.mas_equalTo(TabBarHeight);
        
    }];
    
    [_AgainstListView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(_confirmView.mas_top);
        
    }];
    
}

- (ZGLConfirmSelectView *)confirmView
{
    if (!_confirmView) {
//        CGFloat H = TabBarHeight;
//        CGFloat scrH = UI_SCREEN_HEIGHT;
//        CGFloat scrW = UI_SCREEN_WIDTH;
//        CGFloat h = self.view.bounds.size.height;
//        _confirmView = [[ZGLConfirmSelectView alloc]initWithFrame:CGRectMake(0, h-H-100, scrW, H)];
        _confirmView = [[ZGLConfirmSelectView alloc]initWithFrame:CGRectZero];
        [_confirmView.cleanAllBtn addTarget:self action:@selector(qingKong:) forControlEvents:UIControlEventTouchUpInside];
        //
        [_confirmView.confirmBtn addTarget:self action:@selector(confirmBtn:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _confirmView;
}

- (YUFoldingTableView *)AgainstListView
{
    if (!_AgainstListView) {
//        _AgainstListView = [[YUFoldingTableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-TabBarHeight*2)];
        _AgainstListView = [[YUFoldingTableView alloc]initWithFrame:CGRectZero];
        _AgainstListView.foldingDelegate = self;
        _AgainstListView.foldingState = YUFoldingSectionStateShow;
        self.arrowPosition = 1;
        _AgainstListView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _AgainstListView.backgroundColor = ViewBackgroundColor;
        
        
        //下拉刷新
        WS(weakself)
        MJRefreshNormalHeader *refreshheader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [weakSelf getTheBattleList];
            
        }];
        refreshheader.lastUpdatedTimeLabel.hidden = YES;
        //刷新完操作
        refreshheader.endRefreshingCompletionBlock = ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf cleanAllSelected];
            });
            
        };
        _AgainstListView.mj_header = refreshheader;
        
        /*
         上拉刷新
         */
        
    }

    return _AgainstListView;
}



@end
